package com.mazaiting.jetpack.architecture.live

import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProvider
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.mazaiting.jetpack.R
import kotlinx.android.synthetic.main.activity_live_data.*

class LiveDataActivity : AppCompatActivity() {
  private lateinit var model: NameViewModel
  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_live_data)
    
    // 初始化ViewModel
    model = ViewModelProvider.AndroidViewModelFactory.getInstance(application).create(NameViewModel::class.java)
    // 创建观察者更新UI
    val nameObserver = Observer<String> {
      name: String? ->
      tv_show.text = name
    }
    // 观察LiveData
    model.currentName?.observe(this, nameObserver)
    
    // 修改文本
    btn_change.setOnClickListener {
      val name = "John"
      // 修改数据
      model.currentName?.value = name
    }
  }
}
